package de.tu_cottbus.portal.events;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.struts.LastPath;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.Group;
import com.liferay.portal.model.User;
import com.liferay.portal.security.permission.PermissionChecker;
import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
import com.liferay.portal.security.permission.PermissionThreadLocal;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portal.util.PrefsPropsUtil;
import com.liferay.portal.util.WebKeys;

public class CustomLandingPageAction extends Action {

	@Override
	public void run(HttpServletRequest request, HttpServletResponse response)
			throws ActionException {

		try {
			doRun(request, response);
		} catch (Exception e) {
			throw new ActionException(e);
		}
	}

	protected void doRun(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		long companyId = PortalUtil.getCompanyId(request);

		String path = PrefsPropsUtil.getString(companyId,
				PropsKeys.DEFAULT_LANDING_PAGE_PATH);

		User user = PortalUtil.getUser(request);

		if (user != null) {
			PermissionChecker permissionChecker = PermissionCheckerFactoryUtil
					.create(user);
			PermissionThreadLocal.setPermissionChecker(permissionChecker);

			for (Group site : user.getMySites()) {
				if (site.getName().endsWith("portal")) {
					path = "/group" + site.getFriendlyURL();
					break;
				}
			}
		}

		if (Validator.isNotNull(path)) {
			LastPath lastPath = new LastPath(StringPool.BLANK, path);

			HttpSession session = request.getSession();

			session.setAttribute(WebKeys.LAST_PATH, lastPath);
		}
	}

}
